<script setup>
import DetailForm from '../DetailForm/index.vue'

const { proxy } = getCurrentInstance()

const props = defineProps({
    // eslint-disable-next-line vue/valid-define-props
    ...DetailForm.props,
    modelValue: {
        type: Boolean,
        default: false
    },
    mode: {
        type: String,
        default: 'dialog',
        validator: val => ['dialog', 'drawer'].includes(val)
    }
})

const emit = defineEmits(['update:modelValue', 'success'])

let myVisible = computed({
    get: function() {
        return props.modelValue
    },
    set: function(val) {
        emit('update:modelValue', val)
    }
})

const title = computed(() => props.id == '' ? '新增{{ cname }}' : '编辑{{ cname }}')

function onSubmit() {
    // submit() 为组件内部方法
    proxy.$refs['form'].submit(() => {
        emit('success')
        onCancel()
    })
}

function onCancel() {
    myVisible.value = false
}
</script>

<template>
    <div>
        {{!-- 为什么需要在 dialog 关闭的时候销毁 dialog 中的元素？因为该 dialog 为详情表单，新增的时候会用到，编辑的时候也会用到，不销毁则需要增加代码做处理，例如需要监听当传入的 id，当变 id 更后，需要重新执行生命周期进行表单初始化，同时关闭 dialog 时还需要清空表单，避免出现再次打开 dialog 时表单还保留上一次的信息数据，当表单复杂度上去后，维护这块的成本过高，drawer 同理 --}}
        <el-dialog v-if="props.mode === 'dialog'" v-model="myVisible" :title="title" width="600px" :close-on-click-modal="false" append-to-body destroy-on-close>
            <DetailForm ref="form" v-bind="$props" />
            <template #footer>
                <el-button size="large" @click="onCancel">取 消</el-button>
                <el-button type="primary" size="large" @click="onSubmit">确 定</el-button>
            </template>
        </el-dialog>
        <el-drawer v-else-if="props.mode === 'drawer'" v-model="myVisible" :title="title" size="600px" :close-on-click-modal="false" destroy-on-close>
            <DetailForm ref="form" v-bind="$props" />
            <template #footer>
                <el-button size="large" @click="onCancel">取 消</el-button>
                <el-button type="primary" size="large" @click="onSubmit">确 定</el-button>
            </template>
        </el-drawer>
    </div>
</template>
